package start.spring.basic.job.job.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import start.spring.basic.constant.CommonConstant;
import start.spring.basic.job.service.BaseServiceImpl;
import start.spring.basic.log.LogConstant;
import start.spring.basic.util.common.StringUtil;

/**
 * 
 * ****************************************************************************
 * 自动任务业务逻辑处理实现类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2021年5月7日
 ******************************************************************************
 */
@Slf4j
@Service
public class JobServiceImpl extends BaseServiceImpl implements IJobService {
	
	private AtomicInteger runThreadNum = new AtomicInteger(0);

	@Override
	public void reJobStart(String className) {
		
		//mysql
		String sql = "update GG_PZ_JOB t set t.kssj=now(),t.jssj=null,t.cwxx=null,t.status = '1' where t.jobclass = ? ";
		String[] prams = {className};
		super.dao.excute(sql, prams);
		log.info("自动任务：{}开始执行！", className);
	}

	@Override
	public void reJobEnd(String status, String errMsg, String className, String pch) {
		runThreadNum.getAndDecrement();
		log.info("{}结束任务运行，当前运行任务数：{}", className, runThreadNum.get());
		//是否多线程任务
		boolean multiThreadJob = false;
		if(!StringUtil.isEmpty(pch)) {
			multiThreadJob = true;
		}
		try {
			String msg = "";
			if(errMsg.length()> CommonConstant.ERRMSG_MAX_LENGTH) {
				msg = errMsg.substring(0, CommonConstant.ERRMSG_MAX_LENGTH);
			}else {
				msg = errMsg;
			}
			//记录job表，用于追溯最近一次任务执行状态
			
			//mysql
			String sql = "update GG_PZ_JOB t set t.jssj=now(),t.status = ?,t.cwxx = ? where t.jobclass = ? ";
			String[] prams = {status,msg,className};
			super.dao.excute(sql, prams);
			
			//记录job日志表，用于追溯历史job执行状态
			
			//mysql
			sql = "select t.jobclass,t.jobname,t.status,t.kssj,t.jssj,t.cwxx from GG_PZ_JOB t where t.jobclass = ?";
			prams = new String[]{className};
			List<Map<String, Object>> jobInfoList =super.dao.query(sql, prams);
			Map<String, Object> jobInfo = jobInfoList.get(0);
			
			if(multiThreadJob) {
				//mysql
				sql = "insert into GG_JOB_LOG(ID,JOBCLASS,JOBNAME,STATUS,KSSJ,JSSJ,CWXX,PCH)values(?,?,?,?,?,?,?,?)";
				
				prams = new String[]{idGenerator.nextId(),String.valueOf(jobInfo.get("JOBCLASS")),String.valueOf(jobInfo.get("JOBNAME")),
									String.valueOf(jobInfo.get("STATUS")),String.valueOf(jobInfo.get("KSSJ")),String.valueOf(jobInfo.get("JSSJ")),
									StringUtil.trimObject(jobInfo.get("CWXX"), ""),pch};
				
				super.dao.excute(sql, prams);
			}else {
				//mysql
				sql = "insert into GG_JOB_LOG(ID,JOBCLASS,JOBNAME,STATUS,KSSJ,JSSJ,CWXX,TRACEID)values(?,?,?,?,?,?,?,?)";
				
				prams = new String[]{idGenerator.nextId(),String.valueOf(jobInfo.get("JOBCLASS")),String.valueOf(jobInfo.get("JOBNAME")),
									String.valueOf(jobInfo.get("STATUS")),String.valueOf(jobInfo.get("KSSJ")),String.valueOf(jobInfo.get("JSSJ")),
									StringUtil.trimObject(jobInfo.get("CWXX"), ""),MDC.get(LogConstant.REQUEST_KEY_TRACEID).toString()};
				
				super.dao.excute(sql, prams);
			}
			
		}catch(Exception e) {
			//记录日志出错，不需要后续处理，等待下次调度器自动调度处理
			log.error(e.getMessage(),e);
		}finally {
			//解锁任务的锁定状态
			redis.setex(null, className, String.valueOf(System.currentTimeMillis()), 1);
			if(multiThreadJob) {
				log.info("[{}]:自动任务：{}执行完毕！", pch, className);
			}else {
				log.info("自动任务：{}执行完毕！", className);
			}
		}
	}

	@Override
	public AtomicInteger getRunJobCounter() {
		return this.runThreadNum;
	}

}
